/*
 * Copyright (C) 2011 Jesus Navalon i Pastor <jnavalon at redhermes dot net>
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */

/*
 * pn_VMs.java
 *
 * Created on 23/09/2011, 21:13:51
 */
package kuasar.plugin.servermanager.gui.infoserver;

import java.awt.Color;
import java.awt.Component;
import javax.swing.DefaultListModel;
import javax.swing.JLabel;
import javax.swing.JList;
import javax.swing.JPanel;
import javax.swing.ListCellRenderer;
import kuasar.plugin.utils.Connection;
import kuasar.plugin.utils.Machine;
import kuasar.plugin.utils.SSocketTools;
import kuasar.plugin.utils.Server;
import kuasar.plugin.utils.pn_Info;


/**
 *
 * @author Jesus Navalon i Pastor <jnavalon at redhermes dot net>
 */
public class pn_VMs extends javax.swing.JPanel {

    private String EngineCode,address,ks,user;
    private char[] kspwd, userpwd;
    private int port;
    private DefaultListModel model = new DefaultListModel();
    
    public pn_VMs(String EngineCode, String address, int port, String ks, char[] kspwd, String user, char[] userpwd ) {
        this.EngineCode = EngineCode;
        this.address = address;
        this.port = port;
        this.ks = ks;
        this.user = user;
        this.kspwd = kspwd;
        this.userpwd = userpwd;
        initComponents();
    }

    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        btn_reload = new javax.swing.JButton();
        pn_Left = new javax.swing.JPanel();
        btn_Delete = new javax.swing.JButton();
        btn_Run = new javax.swing.JButton();
        btn_Reset = new javax.swing.JButton();
        btn_Shutdown = new javax.swing.JButton();
        btn_PowerOff = new javax.swing.JButton();
        spn_VMs = new javax.swing.JScrollPane();
        lst_VMs = new javax.swing.JList();

        setCursor(new java.awt.Cursor(java.awt.Cursor.HAND_CURSOR));
        setOpaque(false);

        btn_reload.setIcon(new javax.swing.ImageIcon(getClass().getResource("/kuasar/plugin/servermanager/icons/refresh.png"))); // NOI18N
        btn_reload.setBorderPainted(false);
        btn_reload.setContentAreaFilled(false);
        btn_reload.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btn_reloadActionPerformed(evt);
            }
        });

        pn_Left.setOpaque(false);

        btn_Delete.setBackground(new java.awt.Color(255, 204, 204));
        btn_Delete.setIcon(new javax.swing.ImageIcon(getClass().getResource("/kuasar/plugin/servermanager/icons/delete22.png"))); // NOI18N
        btn_Delete.setText("Delete");
        btn_Delete.setCursor(new java.awt.Cursor(java.awt.Cursor.HAND_CURSOR));
        btn_Delete.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btn_DeleteActionPerformed(evt);
            }
        });

        btn_Run.setBackground(new java.awt.Color(0, 0, 0));
        btn_Run.setForeground(new java.awt.Color(204, 204, 204));
        btn_Run.setIcon(new javax.swing.ImageIcon(getClass().getResource("/kuasar/plugin/servermanager/icons/run.png"))); // NOI18N
        btn_Run.setText("Run          ");
        btn_Run.setCursor(new java.awt.Cursor(java.awt.Cursor.HAND_CURSOR));
        btn_Run.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btn_RunActionPerformed(evt);
            }
        });

        btn_Reset.setBackground(new java.awt.Color(0, 0, 0));
        btn_Reset.setForeground(new java.awt.Color(204, 204, 204));
        btn_Reset.setIcon(new javax.swing.ImageIcon(getClass().getResource("/kuasar/plugin/servermanager/icons/reboot.png"))); // NOI18N
        btn_Reset.setText("Reset       ");
        btn_Reset.setCursor(new java.awt.Cursor(java.awt.Cursor.HAND_CURSOR));
        btn_Reset.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btn_ResetActionPerformed(evt);
            }
        });

        btn_Shutdown.setBackground(new java.awt.Color(0, 0, 0));
        btn_Shutdown.setForeground(new java.awt.Color(204, 204, 204));
        btn_Shutdown.setIcon(new javax.swing.ImageIcon(getClass().getResource("/kuasar/plugin/servermanager/icons/shutdown.png"))); // NOI18N
        btn_Shutdown.setText("Shutdown");
        btn_Shutdown.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btn_ShutdownActionPerformed(evt);
            }
        });

        btn_PowerOff.setBackground(new java.awt.Color(0, 0, 0));
        btn_PowerOff.setForeground(new java.awt.Color(204, 204, 204));
        btn_PowerOff.setIcon(new javax.swing.ImageIcon(getClass().getResource("/kuasar/plugin/servermanager/icons/poweroff.png"))); // NOI18N
        btn_PowerOff.setText("Power Off");
        btn_PowerOff.setCursor(new java.awt.Cursor(java.awt.Cursor.HAND_CURSOR));
        btn_PowerOff.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btn_PowerOffActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout pn_LeftLayout = new javax.swing.GroupLayout(pn_Left);
        pn_Left.setLayout(pn_LeftLayout);
        pn_LeftLayout.setHorizontalGroup(
            pn_LeftLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(pn_LeftLayout.createSequentialGroup()
                .addContainerGap()
                .addGroup(pn_LeftLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(btn_Run, javax.swing.GroupLayout.DEFAULT_SIZE, 331, Short.MAX_VALUE)
                    .addComponent(btn_Reset, javax.swing.GroupLayout.DEFAULT_SIZE, 331, Short.MAX_VALUE)
                    .addComponent(btn_Shutdown, javax.swing.GroupLayout.DEFAULT_SIZE, 331, Short.MAX_VALUE)
                    .addComponent(btn_PowerOff, javax.swing.GroupLayout.DEFAULT_SIZE, 331, Short.MAX_VALUE)
                    .addComponent(btn_Delete, javax.swing.GroupLayout.DEFAULT_SIZE, 331, Short.MAX_VALUE))
                .addContainerGap())
        );
        pn_LeftLayout.setVerticalGroup(
            pn_LeftLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(pn_LeftLayout.createSequentialGroup()
                .addContainerGap()
                .addComponent(btn_Run)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(btn_Reset)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(btn_Shutdown)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(btn_PowerOff)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 58, Short.MAX_VALUE)
                .addComponent(btn_Delete)
                .addContainerGap())
        );

        spn_VMs.setBorder(javax.swing.BorderFactory.createEmptyBorder(1, 1, 1, 1));
        spn_VMs.setViewportBorder(javax.swing.BorderFactory.createEmptyBorder(1, 1, 1, 1));
        spn_VMs.setOpaque(false);

        lst_VMs.setBorder(javax.swing.BorderFactory.createEmptyBorder(1, 1, 1, 1));
        lst_VMs.setModel(model);
        lst_VMs.setCellRenderer(new CellRenderer());
        lst_VMs.setOpaque(false);
        lst_VMs.addListSelectionListener(new javax.swing.event.ListSelectionListener() {
            public void valueChanged(javax.swing.event.ListSelectionEvent evt) {
                lst_VMsValueChanged(evt);
            }
        });
        spn_VMs.setViewportView(lst_VMs);

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(this);
        this.setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(spn_VMs, javax.swing.GroupLayout.PREFERRED_SIZE, 183, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(pn_Left, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addContainerGap())
            .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                .addGroup(layout.createSequentialGroup()
                    .addComponent(btn_reload, javax.swing.GroupLayout.PREFERRED_SIZE, 16, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addContainerGap(552, Short.MAX_VALUE)))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                    .addGroup(layout.createSequentialGroup()
                        .addGap(10, 10, 10)
                        .addComponent(spn_VMs, javax.swing.GroupLayout.DEFAULT_SIZE, 290, Short.MAX_VALUE))
                    .addComponent(pn_Left, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
                .addContainerGap())
            .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                .addGroup(layout.createSequentialGroup()
                    .addComponent(btn_reload)
                    .addContainerGap(298, Short.MAX_VALUE)))
        );

        spn_VMs.getViewport().setOpaque(false);
    }// </editor-fold>//GEN-END:initComponents

    private void lst_VMsValueChanged(javax.swing.event.ListSelectionEvent evt) {//GEN-FIRST:event_lst_VMsValueChanged
        if(!evt.getValueIsAdjusting()){
            String[] data = (String[])lst_VMs.getSelectedValue();
            if(data == null) return;
            boolean running = Boolean.parseBoolean(data[2]);
            btn_Run.setEnabled(!running);
            btn_Reset.setEnabled(running);
            btn_PowerOff.setEnabled(running);
            btn_Shutdown.setEnabled(running);
        }
    }//GEN-LAST:event_lst_VMsValueChanged

    private void btn_RunActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btn_RunActionPerformed
        String[] data = (String []) lst_VMs.getSelectedValue();
        if(data ==null) return;
        SSocketTools st = startInHVMode();
        if(st==null) return;
        boolean status = Machine.startMachine(st, data[1]);
        exitInHVMode(st);
        if(status) loadVMs();
    }//GEN-LAST:event_btn_RunActionPerformed

    private void btn_ResetActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btn_ResetActionPerformed
        String[] data = (String []) lst_VMs.getSelectedValue();
        if(data ==null) return;
        SSocketTools st = startInHVMode();
        if(st==null) return;
        Machine.resetMachine(st, data[1]);
        exitInHVMode(st);
    }//GEN-LAST:event_btn_ResetActionPerformed

    private void btn_ShutdownActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btn_ShutdownActionPerformed
        String[] data = (String []) lst_VMs.getSelectedValue();
        if(data ==null) return;
        SSocketTools st = startInHVMode();
        if(st==null) return;
        Machine.shutDownMachine(st, data[1]);
        exitInHVMode(st);
    }//GEN-LAST:event_btn_ShutdownActionPerformed

    private void btn_PowerOffActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btn_PowerOffActionPerformed
        String[] data = (String []) lst_VMs.getSelectedValue();
        if(data ==null) return;
        SSocketTools st = startInHVMode();
        if(st==null) return;
        boolean status = Machine.powerOffMachine(st, data[1]);
        exitInHVMode(st);
        if(status) loadVMs();
    }//GEN-LAST:event_btn_PowerOffActionPerformed

    private void btn_DeleteActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btn_DeleteActionPerformed
        String[] data = (String []) lst_VMs.getSelectedValue();
        if(data ==null) return;
        SSocketTools st = startInHVMode();
        if(st==null) return;
        Machine.powerOffMachine(st, data[1]);
        boolean status = Machine.deleteMachine(st, data[1]);
        exitInHVMode(st);
        if(status) loadVMs();
    }//GEN-LAST:event_btn_DeleteActionPerformed

    private void btn_reloadActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btn_reloadActionPerformed
        loadVMs();
    }//GEN-LAST:event_btn_reloadActionPerformed

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton btn_Delete;
    private javax.swing.JButton btn_PowerOff;
    private javax.swing.JButton btn_Reset;
    private javax.swing.JButton btn_Run;
    private javax.swing.JButton btn_Shutdown;
    private javax.swing.JButton btn_reload;
    private javax.swing.JList lst_VMs;
    private javax.swing.JPanel pn_Left;
    private javax.swing.JScrollPane spn_VMs;
    // End of variables declaration//GEN-END:variables

    public void loadData(){
        loadVMs();
    }
    private boolean loadVMs(){
        model.removeAllElements();
        SSocketTools st = startInHVMode();
        String[] vms =Machine.getMachines(st);
        for(int i=0; i<vms.length; i++){
            String uuid = Machine.getMachineUUID(st, vms[i]);
            model.addElement(new String[]{vms[i], uuid , Boolean.toString(Machine.isRunning(st, uuid))});
        }
        exitInHVMode(st);
        return true;
    }
    
    private SSocketTools startInHVMode(){
        SSocketTools st = new SSocketTools(address, port, ks, kspwd, user, userpwd);
        if (!st.initSocket()) {
            int status = Connection.checkServer(address, port, ks, kspwd, user, kspwd, false);
            pn_Info.Load((JPanel) this.getParent(), this, "Error connecting to server",
                    "Impossible connect to the server <p> Message error :: " + Connection.getErrorDescription(status),
                    pn_Info.ICON_ERROR);
            
            return null;
        }
        if (!Server.startConnection(st)) {
            pn_Info.Load((JPanel) this.getParent(), this, "Error connecting to server",
                    "It was impossible to connect to the server", pn_Info.ICON_ERROR);
            st.closeAll();
            Connection.removeUserSecret(address);
            return null;
        }
        if(!Server.enterHVMode(st, EngineCode)){
            pn_Info.Load((JPanel) this.getParent(), this, "Error entering to " + EngineCode + " Mode",
                    "There was an error when we're trying to enter to the HV mode", pn_Info.ICON_ERROR);
            st.closeAll();
            return null;
        }
        return st;
    }

    private void exitInHVMode(SSocketTools st) {
        Server.exitHVMode(st);
        Server.closeServer(st);
        st.closeAll();
    }
    
}
class CellRenderer implements ListCellRenderer{

    @Override
    public Component getListCellRendererComponent(JList list, Object value, int index, boolean isSelected, boolean cellHasFocus) {
        String[] data = (String[]) value;
        JLabel label = new JLabel(data[0]);
        label.setForeground(new Color(204,204,204));
        if(isSelected){
            label.setFont(new java.awt.Font("Dialog", 1, 18));
        }
        if(Boolean.parseBoolean(data[2])){
            label.setIcon(new javax.swing.ImageIcon(getClass().getResource("/kuasar/plugin/servermanager/icons/running.png")));
        }else{
            label.setIcon(new javax.swing.ImageIcon(getClass().getResource("/kuasar/plugin/servermanager/icons/stopped.png")));
        }
        return label;
    }
    
}
